import fs from "fs-extra";
import { logger } from "mcp-framework";
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export async function clearMd(clearTime: number) {
    const downloadMdPath = path.join(__dirname, '..', 'download_md')

    if (!fs.existsSync(downloadMdPath)) {
        logger.info(`MD缓存目录不存在: ${downloadMdPath}`);
        return;
    }

    if (clearTime === 0) {
        try {
            await fs.remove(downloadMdPath);
            logger.info(`已清除所有MD缓存: ${downloadMdPath}`);
        } catch (error: any) {
            logger.warn(`清除MD缓存失败，可能文件正在使用中: ${error.message}`);
        }
        return;
    }
    
    const threeDaysAgo = Date.now() - clearTime * 24 * 60 * 60 * 1000;
    const logDirs = fs.readdirSync(downloadMdPath);
    
    for (const dir of logDirs) {
        try {
            const dirPath = path.join(downloadMdPath, dir);
            const stat = fs.statSync(dirPath);
            
            if (stat.isFile()) {
                // 如果是文件，直接检查时间并删除
                if (stat.mtimeMs < threeDaysAgo) {
                    await fs.unlink(dirPath);
                    logger.info(`已删除过期文件: ${dirPath}`);
                }
                continue;
            }
            
            // 如果是目录，遍历其中的文件
            const fileNames = fs.readdirSync(dirPath);
            let hasDeletedFiles = false;
            
            for (const fileName of fileNames) {
                try {
                    const filePath = path.join(dirPath, fileName);
                    const fileStat = fs.statSync(filePath);
                    
                    if (fileStat.mtimeMs < threeDaysAgo) {
                        await fs.unlink(filePath);
                        logger.info(`已删除过期文件: ${filePath}`);
                        hasDeletedFiles = true;
                    }
                } catch (error: any) {
                    logger.warn(`删除文件失败，可能正在使用中: ${path.join(dirPath, fileName)}, ${error.message}`);
                }
            }
            
            // 如果目录为空，尝试删除目录
            const remainingFiles = fs.readdirSync(dirPath);
            if (remainingFiles.length === 0) {
                try {
                    await fs.remove(dirPath);
                    logger.info(`已删除空目录: ${dirPath}`);
                } catch (error: any) {
                    logger.warn(`删除目录失败，可能正在使用中: ${dirPath}, ${error.message}`);
                }
            }
        } catch (error: any) {
            logger.warn(`处理目录失败: ${path.join(downloadMdPath, dir)}, ${error.message}`);
        }
    }
}
